package com.cays.myresearch.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cays.myresearch.MainActivity;
import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.activity.ProjectInfoActivity;
import com.cays.myresearch.adapter.ProjectTitlesAdapter;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.ProjectTitle;
import com.cays.myresearch.entity.Projects;
import com.cays.myresearch.adapter.ProjectsAdapter;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by lenovo on 2018/6/23.
 */

public class EnterpriseProjectFragment extends BaseFragment implements ProjectTitlesAdapter.
        ProjectTitleItemClickListener,ProjectsAdapter.ProjectsClickListener{
    private View view;
    private RecyclerView projectRecyclerView,projectsRV;
    private List<ProjectTitle> projectTitleList=new ArrayList<ProjectTitle> ();
    private List<Projects> projectsList=new ArrayList<Projects> ();
    private ProjectTitlesAdapter projectTitlesAdapter;
    private ProjectsAdapter projectsAdapter;
    private PtrFrameLayout projectHallRefreshPtr;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(view==null){
            view=inflater.inflate(R.layout.enterprise_project_layout,container,false);
        }
        projectRecyclerView=(RecyclerView)view.findViewById (R.id.project_recycler_lists);
        projectsRV=(RecyclerView)view.findViewById (R.id.project_list);
        projectHallRefreshPtr = (PtrFrameLayout)view.findViewById(R.id.project_hall_refresh);
        initProjectTitles();
        initProjects(projectTitleList.get(0));
        initFresh();
        return view;
    }
    private void initProjectTitles(){
        projectTitleList.clear ();
        String []title={"仿生学","电子","计算机","金融"};
        for (int i=0;i<title.length;i++){
            ProjectTitle projectTitle=new ProjectTitle (title[i]);
            projectTitleList.add (projectTitle);
        }
        //主题
        LinearLayoutManager manager=new LinearLayoutManager (getActivity ());
        manager.setOrientation (LinearLayout.HORIZONTAL);
        projectRecyclerView.setLayoutManager (manager);
        projectTitlesAdapter=new ProjectTitlesAdapter (projectTitleList);
        projectRecyclerView.setAdapter (projectTitlesAdapter);
        projectTitlesAdapter.setProjectTitlesListener (this);
    }
    private void initProjects(ProjectTitle projectTitle){
        projectsList.clear ();
        //项目列表
        LinearLayoutManager manager1=new LinearLayoutManager (getActivity ());
        manager1.setOrientation (LinearLayout.VERTICAL);
        projectsRV.setLayoutManager (manager1);
        projectsAdapter=new ProjectsAdapter (projectsList);
        projectsRV.setAdapter (projectsAdapter);
        projectsAdapter.setProjectsClickListenerListener (this);
    }
    public void initFresh(){
        //这里是一个自定义的头部刷新布局,自带的也有一个布局   new PtrDefaultHandler();
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(getActivity());
        projectHallRefreshPtr.addPtrUIHandler(header);
        //不仅仅是添加头布局,还需要设置到控件中 注:特别重要,不然没显示
        projectHallRefreshPtr.setHeaderView(header);
        projectHallRefreshPtr.postDelayed(new Runnable() {
            @Override
            public void run() {
                //执行调用下拉刷新监听
                projectHallRefreshPtr.autoRefresh(false);
            }
        },200);
        //设置下拉刷新监听
        projectHallRefreshPtr.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                refreshProject();
            }
        });
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==1){
                Toast.makeText(getActivity(),"刷新成功",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getActivity(),"未知错误",Toast.LENGTH_SHORT).show();
            }
            projectHallRefreshPtr.refreshComplete();
            projectsAdapter.notifyDataSetChanged();
            return true;
        }
    });
    private void refreshProject(){
        final String url=Constant.URL+"project/list";
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendHttpRequest(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        projectsList.clear();
                        Message message=new Message();
                        message.what=0;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String s=response.body().string();
                        Message message=new Message();
                        projectsList.clear();
                        if(s.contains("~")){
                            List<Projects> pList=Constant.gson.fromJson(s.split("~")[1],
                                    new TypeToken<List<Projects>>(){}.getType());
                            projectsList.addAll(pList);
                            message.what=1;handler.sendMessage(message);
                        }else{
                            message.what=0;handler.sendMessage(message);
                        }
                    }
                });
            }
        }).start();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        MainActivity.currTag= Constant.fragment_enterprise_project;
    }

    @Override
    public void onProjectTitleClick(int position) {
        refreshProject();
    }

    @Override
    public void onProjectsClick(View item, int position) {
        Intent intent=new Intent (getActivity (), ProjectInfoActivity.class);
        String cp=Constant.gson.toJson (projectsList.get (position));
        intent.putExtra ("intent_project",cp);
        startActivity (intent);
    }
}
